package refle;

import lombok.Data;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @author ZhuQi
 * @ClassName Demo
 * @Date 2022/11/7 16:34
 * @Version 1.0
 * @Description 公共的 toString 方法
 */
public class Demo {

    /**
     * User:[name:张三 age:18 list:[1, 2] amount:33.5 ]
     * @param args
     */
    public static void main(String[] args) {
        User user = new User();
        user.setName("张三");
        user.setAge(Integer.valueOf(18));
        ArrayList<String> list = new ArrayList<>();
        list.add("1");
        list.add("2");
        user.setList(list);
        user.setAmount(new BigDecimal("33.5"));
        System.out.println(ToStringUtil.toString(user));
    }
}

@Data
class User{
    private String name;
    private Integer age;

    private List<String> list;

    private BigDecimal amount;
}
class ToStringUtil{

    @SuppressWarnings("all")
    public static String toString(Object obj) {
        if (obj == null) {
            throw new NullPointerException("对象为空");
        }
        StringBuilder stringBuilder = new StringBuilder();
        Class<?> aClass = obj.getClass();
        stringBuilder.append(aClass.getSimpleName() + ":[");

        Field[] declaredFields = aClass.getDeclaredFields();

        for (Field declaredField : declaredFields) {
            try {
                declaredField.setAccessible(true);
                Object o = declaredField.get(obj);
                String name = declaredField.getName();
                stringBuilder.append(name + ":" + o.toString() + " ");
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return stringBuilder.append("]").toString();
    }
}